package com.wondersgroup.fjzlpt.org.service.impl.wdqyhz;

import java.text.SimpleDateFormat;
import java.util.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.quick.framework.exception.ServiceException;
import com.quick.framework.util.ExcelOrWordUtils;
import com.quick.framework.util.FormatDate;
import com.quick.framework.util.LoggerUtil;
import com.wondersgroup.fjzlpt.org.util.ControllerCommonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.wondersgroup.fjzlpt.org.dao.inter.fwb.FwbDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.hzgl.FpfwDao;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.CygxDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.QyxxDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.tdgl.TdjbxxDao;
import com.wondersgroup.fjzlpt.org.dao.inter.tdgl.TdryDao;
import com.wondersgroup.fjzlpt.org.service.inter.wdqyhz.WdqyhzService;

@Service
public class WdqyhzServiceImpl implements WdqyhzService{

	@Autowired
	private FpfwDao fpfwDao;
	@Autowired
	private QyxxDAO qyxxDAO;
	@Autowired
	private TdjbxxDao tdjbxxDao;
	@Autowired
	private TdryDao tdryDao;
	@Autowired
	private FwbDAO fwbDAO;
	@Autowired
	private CygxDAO cygxDAO;

	
	/**
	 * 分页查询已分配任务
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryYfprwByPage(Map<String, String> map){
		JSONObject result = new JSONObject();
		JSONObject tdryObj = new JSONObject();
		//指定团队
		String TDID = map.get("TDID");
		if(!StringUtils.isEmpty(TDID)){
			String[] tdidArr = TDID.split(",");
			for (String tdid : tdidArr) {
				Map<String, String> itemMap = new HashMap<String, String>();
				itemMap.put("TDID", tdid);
				JSONArray tdry = tdryDao.queryTdcylbAll(itemMap);
				tdryObj.put(tdid, tdry);
			}
		}
		map.put("TDIDS", TDID);
		result = fpfwDao.queryYfprwByPage(map);
		this.formatYfprwTdry(result.getJSONArray("rows"), tdryObj);
		return result;
	}
	
	/**
	 * 格式化服务任务--根据团队id添加该团队的成员
	 * @param yfprwArr
	 * @param tdryObj
	 */
	public void formatYfprwTdry(JSONArray yfprwArr, JSONObject tdryObj) {
		for(int i=0;i<yfprwArr.size();i++){
			JSONObject item = yfprwArr.getJSONObject(i);
			item.put("tdryData", tdryObj.getJSONArray(item.getString("YLTDID")));
		}
	}
	
	
	/**
	 * 分页查询我的签约患者
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryPage(Map<String, String> map) {
		ControllerCommonUtil.pageFormat(map);
		map.put("QYLX","01");
//		return qyxxDAO.queryPageForGzt(map);
		return qyxxDAO.queryPageOnView(map);
	}

	/**
	 * 根据签约信息ids查询所有的服务信息
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryFwxxByQyxxids(Map<String, String> map) {
		JSONObject result = new JSONObject();
		try {
			//分页查询待分配服务
			result = qyxxDAO.queryDfprwByPage(map);
			
			//查询待服务人员
			String qyxxArrStr = map.get("qyxxArr");
			if(!StringUtils.isEmpty(qyxxArrStr)){
				JSONArray qyxxArr = JSONArray.parseArray(qyxxArrStr);
				JSONObject dfwryObj = new JSONObject();
				for(int i=0;i<qyxxArr.size();i++){
					Map<String, String> itemMap = (Map)qyxxArr.getJSONObject(i);
					JSONArray dfwryArr = cygxDAO.queryList(itemMap);
					dfwryObj.put(itemMap.get("JMXXID"), dfwryArr);
				}
				result.put("dfwryObj", dfwryObj);
			}
			
			//已分配服务次数
			JSONArray yfprwNumberArr = fpfwDao.queryNumberOfYfprw(map);
			
			this.formatFwxx(result.getJSONArray("rows"), yfprwNumberArr);
			
		} catch (Exception e) {
			result.put("info", "服务信息查询失败！");
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000801","服务信息查询失败！");
		}
		return result;
	}
	
	/**
	 * 格式化服务信息Arr: 在每条记录中加入已分配次数(YFPCS),团队人员
	 * @param fwxxArr
	 * @param yfprwArr
	 * @param yfprwArr
	 */
	private void formatFwxx(JSONArray fwxxArr, JSONArray yfprwArr){
		for(int i=0;i<fwxxArr.size();i++){
			JSONObject fwxx = fwxxArr.getJSONObject(i);
//			fwxx.put("tdryData", tdryObj.getJSONArray(fwxx.getString("YLTDID")));
			for(int j=0;j<yfprwArr.size();j++){
				JSONObject yfprwObj = yfprwArr.getJSONObject(j);
				if(		fwxx.getString("FWID").equals(yfprwObj.getString("FWID"))
				     && fwxx.getString("FWBID").equals(yfprwObj.getString("FWBID"))
				     && fwxx.getString("QYXXID").equals(yfprwObj.getString("QYXXID"))
				 ){
					fwxx.put("YFPCS", yfprwObj.getString("YFPCS"));//已分配次数
					fwxx.put("YWCCS", yfprwObj.getString("YWCCS"));//已完成次数
				}
			}
			if(StringUtils.isEmpty(fwxx.getString("YFPCS"))){
				fwxx.put("YFPCS", "0");//已分配次数
				fwxx.put("YWCCS", "0");//已完成次数
			}
		}
	}

	/**
	 * 保存分配的服务
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject save(Map<String, String> map) {
		ResultObject ro = new ResultObject();
		String method = map.remove("method");
		if("add".equals(method)){
			this.add(map, ro);
		}else{
			this.update(map, ro);
		}
		return (JSONObject)JSON.toJSON(ro);
	}
	
	/**
	 * 新增服务
	 * @param map
	 * @param ro
	 */
	private void add(Map<String, String> map, ResultObject ro){
		try {
			Date nowDate = new Date();
			String fpfwArrStr = map.get("fpfwArr");
			
			JSONArray fpfwArr = JSONArray.parseArray(fpfwArrStr);
			List<Map> fpfwMap = new ArrayList<Map>();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for(int i=0;i<fpfwArr.size();i++){
				Map<String,Object> item = (Map)fpfwArr.getJSONObject(i);
				item.put("FPFWID", UUID.randomUUID().toString());
				item.put("FWZT", "0");
				item.put("YQFWSJ", FormatDate.getDateY_M_D(item.get("YQFWSJ").toString()));
				item.put("XZSJ", nowDate);
				fpfwMap.add(item);
			}
			fpfwDao.insertBatch(fpfwMap);
			ro.setInfo("success","分配任务成功！");
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000802","任务分配保存失败，请稍后重试...");
		}
	}
	
	/**
	 * 更新服务数据：（完成服务/修改服务人员）
	 * @param map
	 * @param ro
	 */
	private void update(Map<String, String> map, ResultObject ro){
		try {
			Date nowDate = new Date();
			String USERID = map.get("USERID");
			JSONArray fpfwArr = JSONArray.parseArray(map.get("fpfwArr"));
			
			for(int i=0;i<fpfwArr.size();i++){
				Map<String,Object> item = (Map)fpfwArr.getJSONObject(i);
				item.put("SJFWRYID",USERID);
				Object SJFWSJ = item.get("SJFWSJ");
				if(SJFWSJ!=null && !"".equals(SJFWSJ)){
					item.put("SJFWSJ", FormatDate.getDateY_M_D(item.get("SJFWSJ").toString()));
				}else{
					item.remove("SJFWSJ");
				}
				Object YQFWSJ = item.get("YQFWSJ");
				if(YQFWSJ!=null && !"".equals(YQFWSJ)){
					item.put("YQFWSJ", FormatDate.getDateY_M_D(item.get("YQFWSJ").toString()));
				}else{
					item.remove("YQFWSJ");
				}
				item.put("XGSJ",nowDate);//修改时间
				fpfwDao.updateForPrimaryKey(item);
			}
			ro.setInfo("success","操作成功！");
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000803","任务操作失败，请稍后重试");
		}
	}

	
	/**
	 * 分页查询已经分配的服务项（已完成/待完成）
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryYfpfwxByPage(Map<String, String> map) {
		return fpfwDao.queryYfprwByPage(map);
	}

	/**
	 * 查询某服务项已经完成的次数和总次数
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryNumberOfYwcrw(Map<String, String> map) {
		JSONObject result = new JSONObject();
		try {
			result = fpfwDao.queryNumberOfYwcrw(map);
			result.put("state", "true");
		} catch (Exception e) {
			result.put("info", "服务次数查询失败！");
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000804","服务次数查询失败！");
		}
		return result;
	}

	/**
	 * 查询团队所有成员  ********该方法随时可能删除*************
	 * @param map
	 * @return
	 */
	@Override
	public JSONArray queryTdry(Map<String, String> map) {
		
		JSONArray tdryArr = tdryDao.queryTdcylbAll(map);
		return tdryArr;
	}
	
	/**
	 * 查询以当前用户作为团队长的团队中相关签约的服务包
	 * @param map
	 * @return
	 */
	public JSONArray queryFwbxxByUserInfo(Map<String, String> map){
		JSONArray tdxxList = tdjbxxDao.queryTdxxByUserInfo(map);
		List<String> tdidList = new ArrayList<String>();
		for(int i=0;i<tdxxList.size();i++){
			JSONObject item = tdxxList.getJSONObject(i);
			tdidList.add(item.getString("TDID"));
		}
		return qyxxDAO.queryFwbByTdid(tdidList.toArray(new String[tdidList.size()]));
	}

	/**
	 * 删除已分配任务
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject deleteYfprw(Map<String, String> map){
		ResultObject ro = new ResultObject();
		try {
			JSONArray deleteData = JSONArray.parseArray(map.get("deleteData"));
			for(int i=0;i<deleteData.size();i++){
				Map deleMap = (Map)deleteData.getJSONObject(i);
				fpfwDao.deleteForPrimaryKey(deleMap);
			}
//			ro.setInfo("success","删除成功");
		} catch (Exception e) {
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000805","删除任务失败,请稍后重试！");
		}
		
		return (JSONObject)JSON.toJSON(ro);
	}
	
	/**
	 * 查询服务居民的基本信息
	 * @param map
	 * @return
	 */
	public JSONObject queryJmxx(Map<String, String> map){
		return qyxxDAO.queryOne(map);
	}

	/**
	 * 查询"查看服务"的标签页统计数目
	 * @param map
	 * @return
	 */
	public JSONObject queryCountInCkfw(Map<String, String> map){
		return fpfwDao.queryCountInCkfw(map);
	}

	/**
	 * 通过居民信息id查询该患者的家庭成员的签约信息
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryJtcyQyxxByJmxxid(Map<String, String> map) {
		JSONObject result = new JSONObject();
		try {
			JSONArray jtcyArr = cygxDAO.queryJtcyQyxxByJmxxid(map.get("JMXXID"));
			//JSONArray jtcyArr = cygxDAO.queryList(map);
			result.put("rows", jtcyArr);
			result.put("state", "true");
		} catch (Exception e) {
			result.put("info", "家庭成员查询失败,请稍后再试..");
			LoggerUtil.error(e.getMessage());
			throw new ServiceException("ERR-000806","家庭成员查询失败,请稍后再试..");
		}
		
		return result;
	}

	/**
	 * 根据用户查询他所拥有的团队的团队成员
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryTdryByUserInfo(Map<String, String> map) {
		JSONArray tdxxList = tdjbxxDao.queryTdxxByUserInfo(map);
		JSONObject tdryObj = new JSONObject();
		for(int i=0;i<tdxxList.size();i++){
			Map itemMap = tdxxList.getJSONObject(i);
			JSONArray tdry = tdryDao.queryTdcylbAll(itemMap);
			tdryObj.put(itemMap.get("TDID").toString(), tdry);
		}
		return tdryObj;
	}

	/**
	 * 查询可以分配任务的家庭成员
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryDfwjm(Map<String, String> map) {
		JSONObject dfwryObj = new JSONObject();
		
		//查询待服务人员
		JSONArray qyxxArr = JSONArray.parseArray(map.get("yfpfwArr"));
		if(!qyxxArr.isEmpty()){
			for(int i=0;i<qyxxArr.size();i++){
				Map<String, String> itemMap = (Map)qyxxArr.getJSONObject(i);
				JSONArray dfwryArr = cygxDAO.queryList(itemMap);
				dfwryObj.put(itemMap.get("JMXXID"), dfwryArr);
			}
		}
		return dfwryObj;
	}

	/**
	 * 导出签约患者数据
	 * @param map
	 * @response
	 */
	@Override
	public void downloadWdqyhz(Map<String, String> map,HttpServletRequest request, HttpServletResponse response) {
		map.put("YLTDID",map.remove("YLTDID_down"));
		JSONArray dataArr = qyxxDAO.queryAllOnView(map);
		//表头
		String titleStr = "{'XM':'姓名','ZJHM':'证件号码','SJHM':'手机号码','JTZZ':'家庭住址','RQFLMC':'人群分类','QYSJ':'签约时间','QYTDMC':'签约团队','QYFWB':'签约服务包'}";
		JSONObject title = JSONObject.parseObject(titleStr);
		dataArr.add(0, title);
		
		//排列循序
		List<String> titleField = new ArrayList<>();
		titleField.add("XM");
		titleField.add("ZJHM");
		titleField.add("SJHM");
		titleField.add("JTZZ");
		titleField.add("RQFLMC");
		titleField.add("QYSJ");
		titleField.add("QYTDMC");
		titleField.add("QYFWB");
		ExcelOrWordUtils.downLoadExcelFile(dataArr, titleField,"我的签约居民",request ,response);
	}
	
	/**
	 * 导出签约患者数据
	 * @param map
	 * @response
	 */
	@Override
	public void downloadYfprw(Map<String, String> map,HttpServletRequest request,HttpServletResponse response) {
		JSONArray dataArr = fpfwDao.queryAll(map);
		//表头
		String titleStr = "{'XM':'签约居民','FWBMC':'签约服务包','FWDX':'服务对象','FWMC':'服务项','FWNR':'服务项内容','QYTD':'签约团队','FWRY':'服务人员','YQFWSJ':'预期服务时间'}";
		JSONObject title = JSONObject.parseObject(titleStr);
		dataArr.add(0, title);
		
		//排列循序
		List<String> titleField = new ArrayList<>();
		titleField.add("XM");
		titleField.add("FWBMC");
		titleField.add("FWDX");
		titleField.add("FWMC");
		titleField.add("FWNR");
		titleField.add("QYTD");
		titleField.add("FWRY");
		titleField.add("YQFWSJ");
		ExcelOrWordUtils.downLoadExcelFile(dataArr, titleField ,"已分配任务", request,response);
	}
	
	/**
	 * 导出服务记录数据（已完成与未完成）
	 * @param map
	 * @response
	 */
	@Override
	public void downloadFwjl(Map<String, String> map,HttpServletRequest request,HttpServletResponse response) {
		String TDIDS = map.get("TDIDS");
		String downTDIDS = map.get("downTDIDS");
		if(StringUtils.isEmpty(TDIDS) && !StringUtils.isEmpty(downTDIDS)){
			map.put("TDIDS", downTDIDS);
		}
		JSONArray dataArr = fpfwDao.queryAll(map);
		//表头
		String titleStr = "{'XM':'签约居民','FWBMC':'签约服务包','FWDX':'服务对象','FWMC':'服务项','FWNR':'服务项内容','QYTD':'签约团队','YQFWSJ':'预期服务时间','SJFWSJ':'实际服务时间'}";
		JSONObject title = JSONObject.parseObject(titleStr);
		dataArr.add(0, title);
		
		//排列循序
		List<String> titleField = new ArrayList<>();
		titleField.add("XM");
		titleField.add("FWBMC");
		titleField.add("FWDX");
		titleField.add("FWMC");
		titleField.add("FWNR");
		titleField.add("QYTD");
		titleField.add("YQFWSJ");
		titleField.add("SJFWSJ");
		ExcelOrWordUtils.downLoadExcelFile(dataArr, titleField,"服务记录",request ,response);
	}
	
	/**
	 * 分页查询签约服务列表到健康城市系统
	 * @param map
	 * @return
	 */
	public JSONObject queryQyfwByPageToJkcs(Map<String, String> map){
		JSONObject result = fpfwDao.queryQyfwByPageToJkcs(map);
		//已分配服务次数
		JSONArray yfprwNumberArr = fpfwDao.queryNumberOfYfprw(map);

		this.formatFwxx(result.getJSONArray("row"), yfprwNumberArr);
		return result;
	}
	
	/**
	 * 分页查询已完成服务列表到健康城市(查看历次)
	 * @param map {QYXXID=xxx,FWBID=xxx,FWID=xxx}
	 * @return
	 */
	public JSONObject queryYwcfwByPageToJkcs(Map<String, String> map){
		return fpfwDao.queryYwcfwByPageToJkcs(map);
	}
	
}
